<script>
    //声明一个树形数据，数据中都会有id和parentId进行相互对应
    let tree=[
        {
            id:1,
            name:"北京",
            parentId:0 ,     
        },
        {
            id:2,
            name:"江苏",
            parentId:0 ,
            children:[
                {
                    id:4,
                    name:"南京",
                    parentId:2 ,     
                },
                {
                    id:5,
                    name:"徐州",
                    parentId:2 ,     
                },
                {
                    id:6,
                    name:"扬州",
                    parentId:2 ,     
                },
            ]      
        },
         {
            id:3,
            name:"安徽",
            parentId:0, 
            children:[
                {
                    id:7,
                    name:"滁州",
                    parentId:3, 
                    children:[
                        {
                            id:9,
                            name:"汊河",
                            parentId:7,     
                        },
                    ]    
                },
                {
                    id:8,
                    name:"合肥",
                    parentId:2 ,     
                },
               
            ]        
        }
    ]
    //声明一个函数，专门将树形转换成扁平数据
    //attr 子节点字段
    function flatTree(data,attr='children'){
        //声明一个数组，存储扁平之后的数据
        let flatArr=[]
        function recursion(arr){
            arr.forEach(item=> {
                if(item[attr]&&item[attr].length>0){
                    recursion(item[attr])
                }
                let obj={}
                let keys=Object.keys(item).filter(key=>key!==attr)
                keys.forEach(key=>{
                    obj[key]=item[key]
                })
                flatArr.push(obj)
            });
        }
        recursion(data)
        return flatArr
    }
    let res=flatTree(tree,"children")
    console.log(res)
</script>